<template>
  <a-card>
    <a-form layout="inline">
      <a-form-item>
        <a-select v-model="listQuery.select_value" style="width: 120px">
          <a-select-option value="全部">全部</a-select-option>
          <a-select-option value="title">标题</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-input-search enterButton @search="onSearch" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" icon="download" @click="downloadFile">下载模板</a-button>
      </a-form-item>
      <a-form-item>
        <a-upload :fileList="fileList" :remove="handleRemove" :beforeUpload="beforeUpload">
          <a-button>
            <a-icon type="upload" />
            选择文件
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleUpload" :disabled="fileList.length === 0" :loading="uploading">{{ uploading ? '正在上传...' : '点击上传' }}</a-button>
      </a-form-item>
      <a-form-item>
        <a-button @click="subpromodal.visible = true" type="primary">科目/方案</a-button>
      </a-form-item>
    </a-form>
    <a-divider type="vertical" />
    <a-table :columns="columns" :dataSource="tabledata" bordered rowKey="id" :pagination="false">
      <template slot="name" slot-scope="text, record, index">
        <span v-if="!record.editable">
          <a href="javascript:;">{{ record.title }}</a>
        </span>
        <span v-else>
          <a-input v-model="record.title" /></span>
      </template>
      <template slot="type" slot-scope="text">
        <a-tag color="pink" v-if="text == 1">单选</a-tag>
        <a-tag color="red" v-else-if="text == 2">多选</a-tag>
        <a-tag color="orange" v-else-if="text == 3">问答</a-tag>
        <a-tag color="green" v-else-if="text == 4">判断</a-tag>
      </template>
      <template slot="aswertype" slot-scope="text, record, index">
        <a-button type="primary" v-if="record.typeid == 1" @click="editAswer(record)">查看/修改</a-button>
        <a-button type="primary" v-else-if="record.typeid == 2" @click="editAswer(record)">查看/修改</a-button>
        <a-tag color="orange" v-else-if="record.typeid == 3">无</a-tag>
        <a-button type="primary" v-else-if="record.typeid == 4" @click="editAswer(record)">查看/修改</a-button>
      </template>
      <template slot="subpro" slot-scope="text, record, index">
        <a-select :disabled="!record.editable" :defaultValue="record.subid" style="width: 120px" @change="value => handleProvinceChange(value, record.id)">
          <a-select-option v-for="(item, index) in subPro" :value="item.subject.id" :key="item.subject.id">{{ item.subject.name }}</a-select-option>
        </a-select>
        <a-select :disabled="!record.editable" v-model="record.projectid" style="width: 120px">
          <a-select-option v-for="(pitem, pindex) in pRo[record.subid]" :key="pitem.id" :value="pitem.id">{{ pitem.name }}</a-select-option>
        </a-select>
      </template>
      <template slot="action" slot-scope="text, record, index">
        <span v-if="!record.editable">
          <a-button type="primary" @click="editExam(record.id)" v-if="text == 1">编辑</a-button>
          <a-button type="dashed" disabled v-else>考试失效无法编辑</a-button>
        </span>
        <span v-else>
          <a-popconfirm v-if="text == 1" title="确定保存?" @confirm="editQuestion(1, record.id)" @cancel="editQuestion(0, record.id)"
            okText="Yes" cancelText="No">
            <a-button type="danger">保存</a-button>
          </a-popconfirm>

          <a-button type="dashed" disabled v-else>考试失效无法编辑</a-button>
        </span>
      </template>
    </a-table>
    <a-pagination showSizeChanger :pageSize.sync="listQuery.page_size" :pageSizeOptions="pagesizeoptions"
      @showSizeChange="onShowSizeChange" :total="total" @change="onChange" v-model="listQuery.page_number" />

    <a-modal title="修改答案" :visible="visible" okText="保存" cancelText="取消" @ok="handleOk" :confirmLoading="confirmLoading"
      @cancel="handleCancel">
      <div v-show="typecode == 1 || typecode == 4">
        <a-input v-for="(item, index) in results" :addonBefore="'[' + item.id + ']:'" :key="item.id" v-model="item.text"></a-input>
        正确答案:
        <a-radio-group :options="options" v-model="dxaswer" @change="radioChange" />
      </div>
      <div v-show="typecode == 2">
        <a-input v-for="(item, index) in results" :addonBefore="'[' + item.id + ']:'" :key="item.id" v-model="item.text"></a-input>
        正确答案:
        <a-checkbox-group :options="options" v-model="dxxaswer" @change="checkChange" />
      </div>
    </a-modal>

    <a-modal title="科目方案修改设置" v-model="subpromodal.visible" @ok="showConfirm" okText="提交" cancelText="取消">
      <span style="color: red;font-size: 14px;">注意：科目名称具有唯一性，方案在同一科目下名称具有唯一性</span>
      <div>
        请选择：
        <a-select style="width: 120px" v-model="subpromodal.subjectid" @change="value => handleSubProvinceChange(value)">
          <a-select-option v-for="(item, index) in subPro" :value="item.subject.id + ''" :key="item.subject.id">{{ item.subject.name }}</a-select-option>
        </a-select>
        <a-select v-model="subpromodal.projectid" style="width: 120px">
          <a-select-option v-for="(pitem, pindex) in pSubRo" :key="pitem.id" :value="pitem.id + ''">{{ pitem.name }}</a-select-option>
        </a-select>
        <a @click="handleSubpro(1)">修改</a>

        <a @click="handleSubpro(2)">添加</a>
      </div>
      <div v-if="subpromodal.action == 1">
        <div class="components-input-demo-size">
          <b style="color: red;">修改:</b>
          <a-input v-model="subpromodal.subtext" />
          <a-input v-model="subpromodal.protext" />
        </div>
      </div>
      <div v-else-if="subpromodal.action == 2">
        <div class="components-input-demo-size">
          <b style="color: red;">添加:</b>
          <a-input v-model="subpromodal.subtext" />
          <a-input v-model="subpromodal.protext" />
        </div>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
  import {
    GeteqQuestions,
    GetSubPro,
    GetResultByQuestionId,
    EditResult,
    UpdateQuestion,
    SaveQuestionByExcel,
    EditSubPro,
    DownModelExcelFile
  } from '@/api/exam';
  import $ from 'jquery';
  import XLSX from 'xlsx';
  export default {
    data() {
      return {
        subpromodal: {
          visible: false,
          action: 0,
          subjectid: null,
          projectid: null,
          subById: {},
          proById: {},
          subtext: null,
          protext: null
        },
        fileList: [],
        uploading: false,
        results: [],
        currenteditdata: null,
        options: [],
        dxaswer: null,
        dxxaswer: null,
        typecode: 0,
        visible: false,
        confirmLoading: false,
        tabledata: [],
        pagesizeoptions: ['20', '50', '200', '5000'],
        columns: [{
            title: 'ID',
            dataIndex: 'id',
            align: 'center',
            sorter: (a, b) => a.id - b.id
          },
          {
            title: '试题标题',
            scopedSlots: {
              customRender: 'name'
            },
            align: 'center',
            sorter: (a, b) => a.title.length - b.title.length
          },
          {
            title: '题目类型',
            dataIndex: 'typeid',
            align: 'center',
            scopedSlots: {
              customRender: 'type'
            },
            filters: [{
                text: '单选',
                value: '1'
              },
              {
                text: '多选',
                value: '2'
              },
              {
                text: '问答',
                value: '3'
              },
              {
                text: '判断',
                value: '4'
              }
            ],
            onFilter: (value, record) => record.typeid == value
          },
          {
            title: '答案',
            align: 'center',
            scopedSlots: {
              customRender: 'aswertype'
            }
          },
          {
            title: '科目/方案',
            align: 'center',
            scopedSlots: {
              customRender: 'subpro'
            }
          },
          {
            title: '操作',
            dataIndex: 'display',
            key: 'x',
            scopedSlots: {
              customRender: 'action'
            },
            align: 'center'
          }
        ],
        listQuery: {
          page_size: 20,
          page_number: 1,
          order_column: 1,
          order_dir: 'asc',
          search_value: '',
          select_value: '全部'
        },
        total: 0,
        subPro: [],
        pRos: {},
        pRo: {},
        pRoName: '',
        pSubRo: {},
        preData: {},
        excelData: []
      };
    },
    watch: {
      pageSize(val) {},
      current(val) {}
    },
    methods: {
      initTable() {
        GeteqQuestions(this.listQuery).then(res => {
          this.tabledata = res.data;
          //只执行一个遍历器即可匹配新版本
          const newData = [...this.tabledata];
          newData.filter(item => {
            item.projectid = item.subproid.split('-')[1] == undefined||item.subproid.split('-')[1] == '' ? '' : Number(item.subproid.split('-')[1]);
            item.subid = Number(item.subproid.split('-')[0]);
          });

          this.tabledata = newData;
          this.total = res.recordsTotal;
          this.setSubPro();
        });
      },
      onShowSizeChange(current, pageSize) {
        this.listQuery.page_size = pageSize;
        this.listQuery.page_number = current;
        this.initTable();
      },
      setSubPro() {
        var _this = this;
        GetSubPro().then(res => {
          _this.subPro = res.data;
          var subPros = res.data;
          for (var i = 0; i < subPros.length; i++) {
            var pros = subPros[i].project;
            _this.subpromodal.subById[subPros[i].subject.id] = subPros[i].subject;
            var prodata = [];
            for (var j = 0; j < pros.length; j++) {
              _this.subpromodal.proById[pros[j].id] = pros[j];
              prodata.push(pros[j]);
            }
            _this.pRos[subPros[i].subject.id] = prodata;
            _this.pRo[subPros[i].subject.id] = _this.pRos[subPros[i].subject.id];
            //设置一个空选项
            let npRo = {
              id: '',
              name: "no select",
            }
             _this.pRo[subPros[i].subject.id].splice(0, 0, npRo);

            //_this.pSubRo[subPros[i].subject.id] = _this.pRos[subPros[i].subject.id];
          }
        });
      },
      handleProvinceChange(value, id) {
        this.pRo[value] = this.pRos[value];
        const newData = [...this.tabledata];
        const target = newData.filter(item => id === item.id)[0];
        if (target) {
          target.projectid = '';
          target.proid = this.pRo[value][0].id;
          target.subid = value;
          this.tabledata = newData;
        }
      },
      handleSubProvinceChange(value) {
        this.pSubRo = this.pRos[value];
        this.subpromodal.projectid = this.pSubRo[0].id + '';
      },
      editAswer(code) {
        this.typecode = code.typeid;
        var query = {
          questionid: code.id
        };
        GetResultByQuestionId(query).then(res => {
          var data = res.data;
          this.results = data;
          const options = [];
          const defaultCheckedList = [];
          for (var i = 0; i < data.length; i++) {
            if (this.typecode == 1 || this.typecode == 4) {
              let option = {
                label: '[' + data[i].id + ']',
                value: data[i].id
              };
              options[i] = option;
              if (data[i].rightr == 1) {
                this.dxaswer = data[i].id;
              }
            } else if (this.typecode == 2) {
              var id = '' + data[i].id;
              options.push(id);
              if (data[i].rightr == 1) {
                defaultCheckedList.push(id);
              }
            }
          }
          if (this.typecode == 2) {
            this.dxxaswer = defaultCheckedList;
          }
          this.options = options;
          this.confirmLoading = false;
          this.visible = true;
        });
      },
      handleOk(e) {
        //更改
        var code = this.typecode;
        var results = this.results;
        if (code == 1 || code == 4) {
          for (var i = 0; i < results.length; i++) {
            if (results[i].id == this.dxaswer) {
              results[i].rightr = 1;
            } else {
              results[i].rightr = 0;
            }
          }
        } else if (code == 2) {
          var aswer = this.dxxaswer;
          for (var i = 0; i < results.length; i++) {
            let ht = false;
            for (var j = 0; j < aswer.length; j++) {
              if (aswer[j] == results[i].id) {
                ht = true;
                break;
              }
            }
            if (ht) {
              results[i].rightr = 1;
            } else {
              results[i].rightr = 0;
            }
          }
        }
        this.confirmLoading = true;

        //console.log(results)
        setTimeout(() => {
          EditResult({
            list: results
          }).then(res => {
            if (res.result) {
              this.visible = false;
              this.confirmLoading = false;
            } else {
              this.confirmLoading = false;
            }
          });
        }, 2000);
      },
      handleCancel(e) {
        this.visible = false;
      },
      radioChange(e) {
        this.dxaswer = e.target.value;
      },
      checkChange(e) {
        this.dxxaswer = e;
      },
      onChange(current) {
        this.listQuery.page_number = current;
        this.initTable();
      },
      editExam(key) {
        const newData = [...this.tabledata];
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
          target.editable = true;
          this.tabledata = newData;
        }
      },
      editQuestion(code, key) {
        const newData = [...this.tabledata];
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
          delete target.editable;
          this.tabledata = newData;
        }
        if (code == 1) {
          var postdata = {
            display: target.display,
            id: target.id,
            pdright: target.pdright,
            subproid: target.subid + '-' + target.projectid,
            title: target.title,
            typeid: target.typeid
          };
          //console.log(postdata);
          UpdateQuestion({
            question: postdata
          }).then(res => {
            if (res.result) {
              this.$message.success('操作成功!', 2);
            } else {
              this.$message.error('操作失败!', 5);
            }
          });
        }
      },
      pdSelectChange(value, id) {
        const newData = [...this.tabledata];
        const target = newData.filter(item => id === item.id)[0];
        if (target) {
          target.pdright = value;
          this.tabledata = newData;
        }
      },
      onSearch(value) {
        this.listQuery.search_value = value;
        this.initTable();
      },
      handleRemove(file) {
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },
      beforeUpload(file) {
        this.fileList = [...this.fileList, file];
        return false;
      },
      handleUpload() {
        var _this = this;
        const {
          fileList
        } = this;
        var refile;
        fileList.forEach(file => {
          refile = file;
        });
        this.uploading = true;
        return new Promise(function(resolve, reject) {
          _this.readExcel(refile).then(
            result => {
              // 此时标识校验成功，为resolve返回
              const isLt2M = refile.size / 1024 / 1024 < 2;
              if (!isLt2M) {
                _this.$message.error('文件大小不能超过2MB!');
              }
              if (isLt2M && result) {
                _this.upLoadChange();
                resolve('校验成功!');
              } else {
                _this.uploading = false;
                reject(false);
              }
            },
            error => {
              // 此时为校验失败，为reject返回
              _this.$message.error(error, 5);
              _this.uploading = false;
              reject(false);
            }
          );
        });

      },
      readExcel(file) {
        // 解析Excel
        let _this = this;
        return new Promise(function(resolve, reject) {
          // 返回Promise对象
          const reader = new FileReader();
          reader.onload = e => {
            // 异步执行
            try {
              // 以二进制流方式读取得到整份excel表格对象
              var data = e.target.result,
                workbook = XLSX.read(data, {
                  type: 'binary'
                });
            } catch (e) {
              reject(e.message);
            }
            _this.excelData = [];
            // 表格的表格范围，可用于判断表头是否数量是否正确
            var fromTo = '';
            // 遍历每张表读取
            for (var sheet in workbook.Sheets) {
              let sheetInfos = workbook.Sheets[sheet];
              // A1,B1,C1...
              let locations = [];
              if (workbook.Sheets.hasOwnProperty(sheet)) {
                fromTo = workbook.Sheets[sheet]['!ref']; // A1:B5
                locations = _this.excelData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
              }
              _this.excelData = locations;
              //console.log(locations);
              var jy = true;
              var ii = 0;
              let alertext = '导入文件有误:';
              for (let i = 1; i < locations.length; i++) {
                ii = i;
                let questiontype = locations[i].questiontype;
                let subpro = locations[i].subpro;
                if (questiontype == '单选' || questiontype == '多选' || questiontype == '判断' || questiontype == '问答') {
                  var sps = _this.subPro;
                  if (sps.length == 0) {
                    jy = false;
                    alertext = '导入文件有误:科目/方案为空，请现在系统中设置！';
                    break;
                  }
                  let subs = subpro.split('/');
                  if (subs.length == 0 || subs.length > 2) {
                    jy = false;
                    alertext = '导入文件有误:科目/方案填写格式错误！';
                    break;
                  }
                  //
                  if (!_this.hasSub(i, subs)) {
                    alertext = '导入文件有误:科目/方案填写错误！';
                    jy = false;
                    break;
                  }
                } else {
                  jy = false;
                  alertext = '导入文件有误:问题类型匹配!';
                  break;
                }
              }
              if (!jy) {
                // 自定的校验规则，自由实现即可
                // 校验失败reject
                reject('在excel表第' + (locations[ii].__rowNum__ + 1) + '行:' + alertext);
              }
              // 校验成功resolve
              resolve(locations);
            }
          };
          reader.readAsBinaryString(file);
        });
      },
      hasSub(ii, val) {
        var sps = this.subPro;
        var hs = false;
        var project;
        for (let i = 0; i < sps.length; i++) {
          if (sps[i].subject.name == val[0]) {
            hs = true;
            this.excelData[ii].subproid = sps[i].subject.id+'-' ;
            project = sps[i].project;
            break;
          }
        }
        if (hs) {
          for (let j = 0; j < project.length; j++) {
            if (project[j].name == val[1]) {
              hs = true;
              this.excelData[ii].subproid += project[j].id;
              break;
            }
          }
        }
        return hs;
      },
      upLoadChange() {
        let pdata = this.excelData;
        var json = {
          questions: []
        };
        let _this = this;
        //异步操作
        var promise = new Promise(function(resolve, reject) {
          for (var i = 1; i < pdata.length; i++) {
            //单选题
            if (pdata[i].questiontype == '单选') {
              //单选答案数组
              let dxresults = [];
              //不正确的答案
              let nrights = pdata[i].resulttext.split('+');
              for (var j = 0; j < nrights.length; j++) {
                let result = {
                  text: nrights[j].trim(),
                  rightr: 0,
                  questionid: '',
                  display: 1
                };
                //存入数组
                dxresults.push(result);
              }
              //正确答案存入数组
              dxresults.push({
                text: pdata[i].resultrightr.trim(),
                rightr: 1,
                questionid: '',
                display: 1
              });
              //问题存入数组
              let question = {
                title: pdata[i].questiontitle.trim(),
                typeid: 1,
                display: 1,
                results: dxresults,
                subproid: pdata[i].subproid
              };
              json.questions.push(question);
            }
            //多选
            else if (pdata[i].questiontype == '多选') {
              let dxxresults = [];
              let zqdas = pdata[i].resultrightr.split('+');
              for (var zq_i = 0; zq_i < zqdas.length; zq_i++) {
                //正确答案存入数组
                dxxresults.push({
                  text: zqdas[zq_i].trim(),
                  rightr: 1,
                  questionid: '',
                  display: 1
                });
              }
              let cwdas = pdata[i].resulttext;
              if (cwdas != undefined && cwdas != '') {
                cwdas = pdata[i].resulttext.split('+');
                for (var cw_i = 0; cw_i < cwdas.length; cw_i++) {
                  //错误答案存入数组
                  dxxresults.push({
                    text: cwdas[cw_i].trim(),
                    rightr: 0,
                    questionid: '',
                    display: 1
                  });
                }
              }
              //多选问题存入数组
              json.questions.push({
                title: pdata[i].questiontitle.trim(),
                typeid: 2,
                display: 1,
                results: dxxresults,
                subproid: pdata[i].subproid
              });
            }
            //问答题(填空题)
            else if (pdata[i].questiontype == '问答') {
              json.questions.push({
                title: pdata[i].questiontitle.trim(),
                typeid: 3,
                display: 1,
                subproid: pdata[i].subproid
              });
            }
            //判断题
            else if (pdata[i].questiontype == '判断') {
              let question = {
                title: pdata[i].questiontitle,
                typeid: 4,
                display: 1,
                results: [],
                subproid: pdata[i].subproid
              };
              if (pdata[i].resultrightr == '对') {
                question.results.push({
                  text: '对',
                  rightr: 1,
                  questionid: '',
                  display: 1
                });
                question.results.push({
                  text: '错',
                  rightr: 0,
                  questionid: '',
                  display: 1
                });
              } else if (pdata[i].resultrightr == '错') {
                question.results.push({
                  text: '错',
                  rightr: 1,
                  questionid: '',
                  display: 1
                });
                question.results.push({
                  text: '对',
                  rightr: 0,
                  questionid: '',
                  display: 1
                });
              }
              json.questions.push(question);
            }
          }

          resolve(true);
        });
        promise.then(function(value) {
          console.log(json);
          SaveQuestionByExcel(json).then(res => {
            if (res.result) {
              _this.fileList = [];
              _this.uploading = false;
              _this.$message.success('上传成功!', 2);
              _this.initTable();
            } else {
              _this.$message.error('上传发生未知错误!', 5);
              _this.uploading = false;
            }
          });
        });
      },
      handleSubpro(code) {
        if (code == 1) {
          this.subpromodal.action = 1;
          this.subpromodal.subtext = this.subpromodal.subById[this.subpromodal.subjectid].name;
          this.subpromodal.protext = this.subpromodal.proById[this.subpromodal.projectid].name;
        } else if (code == 2) {
          this.subpromodal.action = 2;
          this.subpromodal.subtext = this.subpromodal.subById[this.subpromodal.subjectid].name;
          this.subpromodal.protext = this.subpromodal.proById[this.subpromodal.projectid].name;
        }
      },
      showConfirm() {
        let title = '';
        let content = '';
        let code = this.subpromodal.action;
        var _this = this;
        if (code == 1) {
          title = '你确定要执行修改操作吗？';
          content =
            '此操作会修改科目为:' +
            this.subpromodal.subById[this.subpromodal.subjectid].name +
            ',方案为:' +
            this.subpromodal.proById[this.subpromodal.projectid].name +
            '修改成,科目为:' +
            this.subpromodal.subtext +
            ',方案为:' +
            this.subpromodal.protext +
            '吗？';
        } else if (code == 2) {
          title = '你确定要添加新的数据吗？';
          content = '此操作将添加新科目/方案:' + this.subpromodal.subtext + '/' + this.subpromodal.protext;
        }
        let query = {
          subtext: this.subpromodal.subtext,
          protext: this.subpromodal.protext,
          projectid: this.subpromodal.projectid,
          subjectid: this.subpromodal.subjectid,
          action: code
        };
        if (!this.utils.isEmty(query.subtext) && !this.utils.isEmty(query.protext)) {
          this.$confirm({
            title: title,
            content: content,
            onOk() {
              EditSubPro({
                subpro: query
              }).then(res => {
                if (res.result) {
                  _this.$message.success('操作成功!', 2);
                  _this.setSubPro();
                } else {
                  _this.$message.error(res.error, 5);
                }
              });
            },
            onCancel() {
              console.log('Cancel');
            },
            class: 'test'
          });
        } else {
          this.$message.error('您提交的数据有误，请检查！', 5);
          return;
        }
      },
      downloadFile() {
        window.open('/examonline/admin/downModelExcelFile');
      }
    },
    mounted() {
      this.initTable();
    }
  };
</script>
<style scoped>
  .components-input-demo-size .ant-input {
    width: 200px;
    margin: 0 8px 8px 0;
  }
</style>
